import { IObject } from "@/composables/Animation";
import { Path } from "two.js/src/path";
import { Points } from "two.js/src/shapes/points";
import { Group } from "two.js/src/group";
import Two from "two.js";
import { TwoHelper } from "@/composables/TwoHelper";
import { Vector } from "two.js/src/vector";
import { IAnimationConfig, IObjectConfig } from "@/plugins/store";

export class Second implements IObject {
  private path: Group | undefined; // 记录每帧数据的节点
  private core: Path | undefined;
  private two: Two | undefined;
  private twoHelper: TwoHelper | undefined;

  private cfg: IObjectConfig;

  constructor(cfg: IObjectConfig) {
    this.cfg = cfg;
    console.log(`[First] cfg`, this.cfg);
  }

  init(two: Two, cfg: IAnimationConfig): void {
    if (this.cfg) {
      this.two = two;

      this.cfg = {
        ...cfg, // speed 有重叠先 IAnimation
        ...this.cfg,
      };

      this.twoHelper = new TwoHelper(two);

      // 准备画路径的形状
      this.path = two.makeGroup([]);

      // 画物体形状
      this.core = this.twoHelper.makeTriangle(20);
      this.core.noStroke();
      this.core.fill = this.getFill();

      this.core.translation.set(
        this.cfg.x * this.cfg.xScale,
        this.cfg.y * this.cfg.yScale
      );
      this.core.rotation = this.rotation(); // 角度换算弧度
      console.log(`[First] rotation`, this.core.rotation);

      console.log(
        `[First] speed`,
        Math.sin(-this.rotation()) * this.cfg!.speed * 1
      );

      return;
    } else {
      console.error(`[First] 没有执行配置文件的初始化!`);
    }
  }

  private getFill() {
    return this.cfg!.colors && this.cfg!.colors[0]
      ? this.cfg!.colors[0]
      : "rgba(255, 128, 0, 1)";
  }

  private rotation() {
    const rotation = this.twoHelper!.getRadian(this.cfg!.direction);
    return rotation;
  }

  next(frame: number, speed = 1): void {
    this.recordPath();

    this.core!.translation.x +=
      Math.sin(-this.rotation()) * this.cfg!.speed * speed;
    this.core!.translation.y +=
      Math.cos(-this.rotation()) * this.cfg!.speed * speed;
  }

  private recordPath() {
    const point = this.two?.makePoints([
      new Vector(this.core!.translation.x, this.core?.translation.y),
    ]) as Points;

    point.fill = this.getFill();
    this.path?.add(point);
  }
}
